using System;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT;



namespace Microsoft.NETMF.BikeComputer.Hardware
{
    public interface ISwitchSensor
    {
        ulong getSwitchCount();
       
    }

    public class FakeSwitchSensor : IPausable, ISwitchSensor
    {
        private int i = 0;
        private int _gear;

        public FakeSwitchSensor(int gear)
        {
            _gear = gear;
        }

        public  ulong getSwitchCount()
        {
            ulong [] returnvalue = new ulong [] { 8, 5, 8, 9, 10, 7, 11, 12, 6};
            if (_gear == 1) //this is the cadence swtich
            {
                if (i++ >= 8) i = 0;
            }

                return returnvalue[i];
        }

        public void Pause()
        {
            //do nothing in emulation
        }

        public void Resume()
        {
            // do nothing in emulation

        }

    }




    public class SwitchSensor: IPausable, ISwitchSensor
    {

        public SwitchSensor(Cpu.Pin switchPin)
        {
            _switchPin = switchPin;

            Cpu.GlitchFilterTime = new TimeSpan(0, 0, 0, 0, 2);

            switchInterrupt = new InterruptPort(_switchPin, true, Port.ResistorMode.PullDown, Port.InterruptMode.InterruptEdgeHigh);
            switchCounter = 0;
            switchInterrupt.OnInterrupt += new NativeEventHandler(switch_OnInterrupt);
            switchInterrupt.DisableInterrupt();
        }


        private void switch_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            switchCounter++;
            Debug.Print("Pin " + _switchPin.ToString() + " : "  + switchCounter.ToString());
        }


        public void Pause()
        {
            switchInterrupt.DisableInterrupt();
        }

        public void Resume()
        {
            switchCounter = 0;
            switchInterrupt.EnableInterrupt();

        }

        public ulong getSwitchCount()
        {
            ulong returncount = switchCounter;
            switchCounter = 0;
            return returncount;
        }


        private ulong switchCounter;
        private InterruptPort switchInterrupt;
        private Cpu.Pin _switchPin;


    }
}
